﻿using ConcreteService;
using Infrastructures;
using Models;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;

namespace SponsorshipWeb.Controllers
{
    public class StudentController : ApiController
    {
        StudentService service = ServiceFactory.CreateInstance<StudentService>();
        ProjectService projectService = ServiceFactory.CreateInstance<ProjectService>();
        UtilService utilService = ServiceFactory.CreateInstance<UtilService>();
        AssociationService assoService = ServiceFactory.CreateInstance<AssociationService>();
        UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();

        #region 学生社团查看
        /// <summary>
        /// 获得社团首页信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        [HttpGet]
        public IHttpActionResult GetAssociation()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userID = user.UserID;
            var userinfo = userService.Get<UserInfo>(userID.ToString());
            var asso = assoService.GetAssociationByUserID(userID);
            Dictionary<string, string> dic = new Dictionary<string, string>();
            if (asso != null)
            {
                dic = asso.ToDictionary();
                dic.Add("SchoolName", asso.School.SchoolName);
            }
            dic.AddOrReplace("Status", userinfo.Status.ToString());
            dic.AddOrReplace("LogoPath", SystemConfig.Get("UploadHttpPath") + userinfo.HeadImage);
            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        /// <summary>
        /// 负责人信息 + 修改负责人信息
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        [HttpGet]
        public IHttpActionResult GetStuInfo()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();
            var userinfo = userService.Get<UserInfo>(userID);

            Dictionary<string, string> dic = userinfo.ToDictionary();
            var student = service.Get<Student>(userID);
            if (student != null)
            {
                dic.Add("StudentName", student.Name);
                dic.Add("Major", student.Major);
                dic.Add("Education", student.Education);
                dic.Add("StudentLDNO", student.StudentLDNO);
                dic.Add("EnterYear", student.EntranceDate.Year.ToString());
                try
                {
                    dic.Add("School", AppConfig.GetSchool(student.SchoolNO).SchoolName);
                }
                catch
                {

                }
            }

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        #endregion

        #region 学生注册

        /// <summary>
        /// 学生注册第三步
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        public IHttpActionResult RegisterSecond()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();
            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;
            HttpPostedFile logo = httpPostedFile[0];
            var stu = service.Get<Student>(userID);
            var userinfo = userService.Get<UserInfo>(userID);

            #region 读取表单信息

            string name = httpPostedForm["name"];
            string remark = httpPostedForm["Remark"];
            string belongName = httpPostedForm["belongName"];
            string nature = httpPostedForm["nature"];
            int school = stu.SchoolNO;
            string type = httpPostedForm["type"];
            string typedetail = httpPostedForm["typedetail"];
            string amount = httpPostedForm["amount"];
            string deptAmount = httpPostedForm["deptAmount"];
            string schoolAddress = httpPostedForm["schoolAddress"];

            #endregion

            #region 创建社团

            Association obj = new Association(name, userID.ToInt(), nature, type.ToInt(), typedetail.ToInt(), school, amount.ToInt(), deptAmount.ToInt(), remark, "", schoolAddress, belongName, AppConfig.GetDefauleAssocGrade());
            var assorelation = utilService.ListRelationship(RelationshipFun.AssociationToStudent, userID.ToInt()).FirstOrDefault();
            if (assorelation != null)
            {
                var asso = assoService.Get<Association>(assorelation.NOFrom.ToString());
                obj.CreateTime = assorelation.CreateTime;
                obj.AssociationNO = asso.AssociationNO;
                obj.SelfPassword = asso.SelfPassword;
                obj.UserPassword = asso.UserPassword;
                assoService.Update<Association>(obj, userID);
            }
            else
            {
                obj = assoService.Create<Association>(obj, userID.ToInt().ToString());
                Relationship relationship = new Relationship(obj.AssociationNO, obj.Name, RelationshipFun.AssociationToStudent, stu.StudentNO, stu.Name);
                utilService.CreateRelationship(relationship, userID);
            }

            #endregion

            #region 保存Logo
            string path = FileUtil.SaveFile(logo, FileType.AssoLogo, obj.AssociationNO, userID, APPRole.Association);
            obj.LogoPath = path;
            assoService.Update(obj, userID);
            #endregion

            #region 更新用户信息
            userinfo.HeadImage = path;
            userinfo.Status = CommonStatus.FourStep;
            userService.Update(userinfo, userID);
            #endregion

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "4"
            });
        }

        /// <summary>
        /// 学生社团注册最后一步
        /// </summary>
        /// <returns></returns>
        [CommonAuthorize]
        [UserRole(APPRole.Student)]

        public IHttpActionResult RegisterFourth()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            int userid = user.UserID;

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;

            HttpPostedFile StuIDCardContent = httpPostedFile["StuIDCardContent"];
            HttpPostedFile StuIDCardCover = httpPostedFile["StuIDCardCover"];

            FileUtil.SaveFile(StuIDCardContent, FileType.StuIDCardContent, userid, userid.ToString(), APPRole.Student);
            FileUtil.SaveFile(StuIDCardCover, FileType.StuIDCardCover, userid, userid.ToString(), APPRole.Student);

            string LDID = httpPostedForm["LDID"];
            string AliPayNo = httpPostedForm["AliPayNo"];
            string BankNo = httpPostedForm["BankNo"];

            var lstse = utilService.ListSeldomUsed(userid, SeldomType.All, APPRole.Student);
            SeldomUsed se1 = new SeldomUsed(userid, APPRole.Student, SeldomType.PersonCardNo, LDID);
            SeldomUsed se2 = new SeldomUsed(userid, APPRole.Student, SeldomType.AliPayNo, AliPayNo);
            SeldomUsed se3 = new SeldomUsed(userid, APPRole.Student, SeldomType.BankNo, BankNo);

            var existSe1 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.PersonCardNo).FirstOrDefault();
            var existSe2 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.AliPayNo).FirstOrDefault();
            var existSe3 = lstse.Where(x => x.BelongNo == userid && x.Type == SeldomType.BankNo).FirstOrDefault();

            if (existSe1 == null)
            {
                utilService.CreateSeldomUsed(se1, userid.ToString());
            }
            else
            {
                existSe1.Value = LDID;
                utilService.UpdateSeldomUsed(existSe1, userid.ToString());
            }
            if (existSe2 == null)
            {
                utilService.CreateSeldomUsed(se2, userid.ToString());
            }
            else
            {
                existSe2.Value = LDID;
                utilService.UpdateSeldomUsed(existSe2, userid.ToString());
            }
            if (existSe3 == null)
            {
                utilService.CreateSeldomUsed(se3, userid.ToString());
            }
            else
            {
                existSe3.Value = LDID;
                utilService.UpdateSeldomUsed(existSe3, userid.ToString());
            }

            UserInfo userinfo = userService.Get<UserInfo>(userid.ToString());
            userinfo.Status = CommonStatus.FiveStep;
            userService.Update(userinfo, userid.ToString());
            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "5"
            });
        }

        /// <summary>
        /// 学生社团注册第二步（负责人信息）
        /// </summary>
        /// <returns></returns>

        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        public IHttpActionResult RegisterThird()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userid = user.UserID.ToString();

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["name"];
            string Major = httpPostedForm["Major"];
            string EntranceDate = httpPostedForm["EntranceDate"];
            string Education = httpPostedForm["Education"];
            string StudentLDNO = httpPostedForm["StudentLDNO"];
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            string school = httpPostedForm["school"];

            Student stu = new Student(userid.ToInt(), name, StudentLDNO, Education, Major, school.ToInt(), EntranceDate.ToDateTime());
            Student exist = service.Get<Student>(userid);
            if (exist != null)
            {
                stu.StudentNO = exist.StudentNO;
                stu.CreateTime = exist.CreateTime;
                service.Update(stu, userid);
            }
            else
            {
                service.Create(stu, userid);
            }
            var userinfo = userService.Get<UserInfo>(userid);
            userinfo.Phone = phone;
            userinfo.QQ = qq;
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Role = APPRole.Student;
            userinfo.Status = CommonStatus.ThirdStep;
            userinfo.NickName = name;
            userService.Update(userinfo, userid);

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "3"
            });
        }

        #endregion

        #region 学生社团和负责人修改

        /// <summary>
        /// 修改社团信息
        /// </summary>
        /// <returns></returns>

        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        public IHttpActionResult UpdateAssociation()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();
            string userID = user.UserID.ToString();

            var httpPostedForm = HttpContext.Current.Request.Form;
            var stu = service.Get<Student>(userID);
            Association asso = assoService.GetAssociationByUserID(userID.ToInt());
            if (stu == null || asso == null)
            {
                return BadRequest("请完善社团资料");
            }
            var userinfo = userService.Get<UserInfo>(userID);

            string name = httpPostedForm["name"];
            string remark = httpPostedForm["Remark"];
            string belongName = httpPostedForm["belongName"];
            string nature = httpPostedForm["nature"];
            int school = stu.SchoolNO;
            string type = httpPostedForm["type"];
            string typedetail = httpPostedForm["typedetail"];
            string amount = httpPostedForm["amount"];
            string deptAmount = httpPostedForm["deptAmount"];
            string schoolAddress = httpPostedForm["schoolAddress"];

            #region Association
            asso.Name = name;
            asso.Remark = remark;
            asso.ChargeName = belongName;
            asso.SchoolType = nature;
            asso.TypeNO = type.ToInt();
            asso.TypeDetailNO = typedetail.ToInt();
            asso.SchoolNO = school;
            asso.ScaleNO = amount.ToInt();
            asso.DeptAmount = deptAmount.ToInt();
            asso.SchoolAddress = schoolAddress;
            asso.UpdateTime = DateTime.Now;
            assoService.Update<Association>(asso, userID.ToInt().ToString());
            #endregion
            var httpPostedFile = HttpContext.Current.Request.Files;

            
            HttpPostedFile StuIDCardContent = httpPostedFile["StuIDCardContent"];
            HttpPostedFile StuIDCardCover = httpPostedFile["StuIDCardCover"];

            if (StuIDCardContent.ContentLength != 0)
                FileUtil.SaveFile(StuIDCardContent, FileType.StuIDCardContent, user.UserID, user.UserID.ToString(), APPRole.Student);
            if (StuIDCardCover.ContentLength != 0)
                FileUtil.SaveFile(StuIDCardCover, FileType.StuIDCardCover, user.UserID, user.UserID.ToString(), APPRole.Student);

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "OK"
            });
        }

        /// <summary>
        /// 修改负责人信息
        /// </summary>
        /// <returns></returns>

        [CommonAuthorize]
        [UserRole(APPRole.Student)]
        public IHttpActionResult UpdateStudent()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest("请登录");
            string userid = user.UserID.ToString();

            var httpPostedFile = HttpContext.Current.Request.Files;
            var httpPostedForm = HttpContext.Current.Request.Form;

            string name = httpPostedForm["name"];
            string Major = httpPostedForm["Major"];
            string EntranceDate = httpPostedForm["EntranceDate"];
            string Education = httpPostedForm["Education"];
            string StudentLDNO = httpPostedForm["StudentLDNO"];
            string phone = httpPostedForm["phone"];
            string qq = httpPostedForm["qq"];
            string wechart = httpPostedForm["wechart"];
            string email = httpPostedForm["email"];
            string school = httpPostedForm["school"];

            Student stu1 = service.Get<Student>(userid);
            if (stu1 == null)
                return BadRequest("请完善社团资料");

            stu1.Name = name;
            stu1.Major = Major;
            stu1.EntranceDate = EntranceDate.ToDateTime();
            stu1.Education = Education;
            stu1.StudentLDNO = StudentLDNO;

            service.Update<Student>(stu1, userid);
            var userinfo = userService.Get<UserInfo>(userid);

            userinfo.Phone = phone;
            userinfo.QQ = qq;
            userinfo.WeChart = wechart;
            userinfo.Email = email;
            userinfo.Role = APPRole.Student;
            userinfo.NickName = name;
            userService.Update(userinfo, userid);

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = "OK"
            });
        }
        #endregion



        // GET api/student
        public IHttpActionResult Get()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();

            var student = service.Get<Student>(user.UserID.ToString());
            if (student == null)
                return BadRequest();

            return Ok(new ObjectResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseObj = student
            });
        }

        [HttpGet]
        public IHttpActionResult GetAssocInfo()
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();

            var assoc = assoService.GetRelationship(user.UserID, RelationshipFun.AssociationToStudent);
            if (assoc == null)
                return BadRequest();

            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic.Add("Name", assoc.Name);
            dic.Add("AssociationGrade", assoc.AssociationGrade.ToString());

            return Ok(new DictResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseDict = dic
            });
        }

        [HttpGet]
        public IHttpActionResult ListSchool()
        {
            var lst = AppConfig.ListSchool();

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpGet]
        public IHttpActionResult ListAmount()
        {
            var lst = AppConfig.ListRuleByFun(BaseDataFun.AssociationSize);

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpGet]
        public IHttpActionResult ListBaseData()
        {
            var lst = AppConfig.ListRuleByFun(BaseDataFun.AssosiationType);

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        [HttpGet]
        public IHttpActionResult ListArea()
        {
            var lst = AppConfig.ListArea(AreaFun.City);

            return Ok(new ListResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseList = lst.Select(x => (Object)x).ToList()
            });
        }

        // GET api/student/5
        public string Get(int id)
        {
            return "value";
        }

        // POST api/student
        public IHttpActionResult Post([FromBody]Student value)
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();

            Student stu = new Student();
            stu.StudentNO = user.UserID;
            stu.StudentNO = value.StudentNO;
            //stu.SchoolName = value.SchoolName;
            stu.Major = value.Major;
            stu.Education = value.Education;
            stu.EntranceDate = value.EntranceDate;
            stu.StudentLDNO = value.StudentLDNO;
            stu.Name = value.Name;
            //stu.Status = CommonStatus.Pending;

            service.Create(stu, user.UserID.ToString());

            UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
            var userInfo = userService.Get<UserInfo>(user.UserID.ToString());

            //userInfo.Email = value.BankNO;
            //userInfo.QQ = value.AliPayNO;

            userService.Update(userInfo, user.UserID.ToString());

            //user.StudentID = value.StudentNO;
            //AuthUtil.UpdateAuthentication(user);

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = value.StudentNO.ToString()
            });
        }

        // PUT api/student/5
        public IHttpActionResult Put([FromBody]Student value)
        {
            var user = AuthUtil.GetAuthentication();
            if (user == null)
                return BadRequest();

            var stu = service.Get<Student>(user.UserID.ToString());
            //stu.SchoolNO = value.SchoolNO;
            //stu.SchoolName = value.SchoolName;
            stu.Major = value.Major;
            stu.Education = value.Education;
            stu.EntranceDate = value.EntranceDate;
            stu.StudentLDNO = value.StudentLDNO;
            stu.Name = value.Name;
            //stu.Status = CommonStatus.Pending;

            service.Update(value, user.UserID.ToString());

            UserInfoService userService = ServiceFactory.CreateInstance<UserInfoService>();
            var userInfo = userService.Get<UserInfo>(user.UserID.ToString());

            //userInfo.Email = value.BankNO;
            //userInfo.QQ = value.AliPayNO;

            userService.Update(userInfo, user.UserID.ToString());

            return Ok(new StringResponse()
            {
                Status = ResponseStatus.OK(),
                ResponseStr = value.StudentNO.ToString()
            });
        }












        // DELETE api/student/5
        public void Delete(int id)
        {
        }
        private string SaveFile(HttpPostedFile fu, FileType type, IList<FileSystem> lst, int belongNO, string userid, APPRole role)
        {
            string fileName = fu.FileName;

            string fileExt = Path.GetExtension(fileName);

            string strDir = SystemConfig.Get("UploadPath") + "\\Student\\" + userid + "\\" + belongNO + "\\";

            if (!Directory.Exists(strDir))
                Directory.CreateDirectory(strDir);

            string strSysName = type.ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + fileExt;
            fu.SaveAs(strDir + strSysName);

            FileSystem fs = null;

            if (lst != null && lst.Count > 0)
                fs = lst.FirstOrDefault(x => x.Fun == type);
            else
                fs = new FileSystem();

            fs.Fun = type;
            fs.TypeName = role;
            fs.BelongNO = belongNO;
            fs.NewName = strSysName;
            fs.OldName = fileName;
            fs.Path = SystemConfig.Get("UploadHttpPath") + "Student/" + userid + "/" + belongNO + "/" + strSysName;
            fs.Status = CommonStatus.Active;
            fs.InstanceID = SystemConfig.Get("InstanceID");
            fs.CreateUser = userid.ToInt();
            fs.CtreateTime = DateTime.Now;


            if (lst == null || lst.Count == 0)
                utilService.CreateFileSystem(fs, userid);
            else
                utilService.UpdateFileSystem(fs, userid);
            return fs.Path;
        }
    }
}
